"ui";
let FileChooserDialog = require("./res/file_chooser_dialog");

let file = function() {
    let file;
    let suo = {};
    try {
        file = JSON.parse(files.read("./配置.json"));
    } catch (err) {
        file = {};
    }
    suo.read = function(key) {
        return file[key];
    };
    suo.add = function(key, data) {
        file[key] = data;
    };
    suo.save = function() {
        files.write("./配置.json", JSON.stringify(file,null,'\t'));
        toastLog("保存完成");
    };
    return suo;
}();

let iofile = !!file.read("iofile");//是否扫描隐藏文件
let ismedia = !!file.read("ismedia");//是否媒体扫描
var color = "#009688";

ui.layout(
    <drawer id="drawer">
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="设置"/>
                <tabs id="tabs"/>
            </appbar>
            <viewpager id="viewpager">
                <frame>
                    <vertical>
                        <text padding="8 3 8 3" text="请在这里添加需要整理的文件夹，每次运行将扫描这些文件夹里的内容。支持子文件夹扫描，深度代表子文件夹层数" textColor="#aa3388" textSize="17sp" maxLines="3" />
                        <checkbox id="iofile" checked={iofile} text="是否扫描以“.”开头的隐藏文件/文件夹" />
                        <checkbox id="ismedia" checked={ismedia} text="移动完成后通知媒体扫描这些文件" />
                        <list id="todoList">
                            <card w="*" h="80" margin="10 5" cardCornerRadius="2dp"
                            cardElevation="1dp" foreground="?selectableItemBackground">
                            <horizontal gravity="center_vertical">
                                <View bg="{{this.color}}" h="*" w="10" />
                                <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                    <text text="{{this.dir}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                    <horizontal>
                                    <text text="搜索深度：{{this.sdt}}，  " textColor="#999999" textSize="14sp" maxLines="1" />
                                    <text text="大小限制：{{this.sizeSet?((this.sizeSet.minSize+'～'+(this.sizeSet.maxSize||'无限制'))+'（kb）'):'无限制'}}" />
                                    </horizontal>
                                </vertical>
                                
                            </horizontal>
                            
                        </card>
                    </list>
                </vertical>
                <fab id="add" w="auto" h="auto" src="@drawable/ic_add_black_48dp"
                margin="16" layout_gravity="bottom|right" tint="#ffffff" />
            </frame>
            <frame>
                <vertical>
                    <text padding="8 3 8 3" text="请在这里添加文件移动的规则，将会把扫描到的文件以指定后缀名的文件移动到下方的文件夹，全局生效，如有重复后添加的优先" textColor="#aa3388" textSize="17sp" maxLines="3" />
                    <list id="todoList2">
                        <card w="*" h="80" margin="10 5" cardCornerRadius="2dp"
                        cardElevation="1dp" foreground="?selectableItemBackground">
                        <horizontal gravity="center_vertical">
                            <View bg="{{this.color}}" h="*" w="10" />
                            <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                <text text="{{this.tofile}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                <text text="保存文件类型:{{JSON.stringify(this.name||[])}}" textColor="#999999" textSize="14sp" />
                            </vertical>
                            
                        </horizontal>
                        
                    </card>
                </list>
            </vertical>
            <fab id="add2" w="auto" h="auto" src="@drawable/ic_add_black_48dp"
            margin="16" layout_gravity="bottom|right" tint="#ffffff" />
        </frame>
        <frame>
            <vertical>
                <text padding="8 3 8 3" text="这里为第一页每个要整理文件夹单独配置移动规则，如果与全局规则重复，独立规则优先" textColor="#aa3388" textSize="17sp" maxLines="3" />
                <list id="todoList3">
                    <card w="*" h="80" margin="10 5" cardCornerRadius="2dp"
                    cardElevation="1dp" foreground="?selectableItemBackground">
                    <horizontal gravity="center_vertical">
                        <View bg="{{this.color}}" h="*" w="10" />
                        <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                            <text  text="{{this.dir}}" textColor="#222222" textSize="16sp" maxLines="1" />
                            <text id="txta" text="独立规则数量：{{this.moshi?this.moshi.length:'无'}}" textColor="#999999" textSize="14sp" maxLines="2" />
                        </vertical>
                        
                    </horizontal>
                    
                </card>
            </list>
        </vertical>
    </frame>
    </viewpager>
    </vertical>
    </drawer>
);


//创建选项菜单(右上角)
ui.emitter.on("create_options_menu", menu => {
    menu.add("设置");
    menu.add("说明");
    menu.add("关于");
});
//监听选项菜单点击
ui.emitter.on("options_item_selected", (e, item) => {
    switch (item.getTitle()) {
        case "设置":
            toast("还没有设置");
            break;
        case "关于":
            alert("关于", "作者：selp\nqq:201228773\n文件选择器引用的官方示例");
            break;
        case "说明":
             alert("这个工具可以将各种类型文件分别整理到一个文件夹下，配置好后可以配合Tasker或者MacroDroid等工具做到自动化整理。");
             break;
    }
    e.consumed = true;
});
activity.setSupportActionBar(ui.toolbar);
//设置滑动页面的标题
ui.viewpager.setTitles(["整理文件夹", "移动规则(全局)", "独立规则"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);



var todoList = file.read("data") || [];
let moshiList = file.read("moshi") || [];
var materialColors = ["#e91e63", "#ab47bc", "#5c6bc0", "#7e57c2", "#2196f3", "#00bcd4",
    "#26a69a", "#4caf50", "#8bc34a", "#ffeb3b", "#ffa726", "#78909c", "#8d6e63"
];
!! function() { //第一页的配置
    ui.iofile.on("check", checked => iofile = checked);
    ui.ismedia.on("check", checked => ismedia = checked);
    ui.todoList.setDataSource(todoList);
    ui.todoList.on("item_long_click", function(e, item, i, itemView, listView) {
        confirm("确定要删除" + "吗？")
            .then(ok => {
                if (ok) {
                    todoList.splice(i, 1);
                }
            });
        e.consumed = true;
    });
    ui.todoList.on("item_click", function(item, i, itemView, listView) {
        let dir = todoList[i].dir;
        setxd(dir, function(ojb) {
            todoList[i] = ojb;
        });
    });
    ui.add.on("click", () => {
        vtc(function(dir) {
            setxd(dir, function(ojb) {
                todoList.push(ojb);
            });
        });
    });

    function setxd(dir, funt) {
        if (!dir) return;
            let view = ui.inflate(
                <vertical>
                  <text text="请输搜索子目录深度(0～5)：" />
                  <input id="sdt" inputType="number" text="0"/>
                  <text text="文件大小过滤：（留空则不限制）" />
                  <horizontal>
                  <input id="minSize" hint="最小/kb" layout_weight="1" inputType="number" text=""/>
                  <text text="～" />
                  <input id="maxSize" hint="最大/kb" layout_weight="1" inputType="number" text=""/>
                  </horizontal>
                </vertical>, null, false
            );
        dialogs.build({
            customView: view,
            title: "设置",
            positive: "确定",
            autoDismiss: false,
            wrapInScrollView: true
        }).on("positive", function(dialog) {
           let sdt = Number(view.sdt.text());
           let minSize = Number(view.minSize.text());
           let maxSize = Number(view.maxSize.text());
          if (sdt === NaN || sdt < 0 || sdt > 5) return toast("请输入0-5的数字");
          let sizeSet = {
              maxSize:maxSize,
              minSize:minSize
              }
           funt({
                    dir: dir,
                    sdt: sdt,
                    sizeSet:sizeSet,
                    color: materialColors[random(0, materialColors.length - 1)]
                });
          dialog.dismiss();
        }).show();
    }
}();
!! function() { //第2页的配置
    ui.todoList2.setDataSource(moshiList);
    ui.todoList2.on("item_long_click", function(e, item, i, itemView, listView) {
        confirm("确定要删除" + "吗？")
            .then(ok => {
                if (ok) {
                    moshiList.splice(i, 1);
                }
            });
        e.consumed = true;
    });
    ui.todoList2.on("item_click", function(item, i, itemView, listView) {
        let file = moshiList[i].tofile;
        filefz(file, function(ojb) {
            moshiList[i] = ojb;
        },moshiList[i].name);
    });
    ui.add2.on("click", () => {
        vtc(function(dir) {
            filefz(dir, function(ojb) {
                moshiList.push(ojb);
            });
        });
    });
}();
//第三页配置
!! function() {
    ui.todoList3.setDataSource(todoList);
    ui.todoList3.on("item_click", function(item, i, itemView, listView) {
        let data = todoList[i];
        let moshi = data.moshi || [];
        let view = ui.inflate(
            <frame>
                        <vertical>
                            <list id="todoList">
                                <card w="*" h="80" margin="0 3" cardCornerRadius="2dp"
                                cardElevation="1dp" foreground="?selectableItemBackground">
                                <horizontal gravity="center_vertical">
                                    <View bg="{{this.color}}" h="*" w="10" />
                                    <vertical padding="7 8" h="auto" w="0" layout_weight="1">
                                        <text text="{{this.tofile}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                        <text text="{{'文件类型：'+JSON.stringify(this.name)}}" textColor="#999999" textSize="14sp" maxLines="2" />
                                    </vertical>
                                    
                                </horizontal>
                                
                            </card>
                        </list>
                    </vertical>
                    <fab id="add" w="auto" h="auto" src="@drawable/ic_add_black_48dp"
                    margin="16" layout_gravity="bottom|right" tint="#ffffff" />
                    </frame>, null, false
        );
        view.todoList.setDataSource(moshi);
        view.todoList.on("item_long_click", function(e, item, i, itemView, listView) {
            confirm("确定要删除" + "吗？")
                .then(ok => {
                    if (ok) {
                        moshi.splice(i, 1);
                    }
                });
            e.consumed = true;
        });
        view.todoList.on("item_click", function(item, i, itemView, listView) {
            let file = moshi[i].tofile;
            filefz(file, function(ojb) {
                moshi[i] = ojb;
            },moshi[i].name);
        });
        view.add.on("click", function() {
            vtc(function(dir) {
                filefz(dir, function(ojb) {
                    moshi.push(ojb);
                });
            });
        });

        dialogs.build({
            customView: view,
            title: "规则列表",
            wrapInScrollView: true
        }).on("dismiss", function() {
            data.moshi = moshi;
            todoList[i] = data;
            itemView.txta.text("自定义规则数量：" + moshi.length);
        }).show();

    });

}();

function vtc(funt) {
    threads.start(function() {
        FileChooserDialog.build({
                title: '请选择要移至的文件夹',
                dir: "/sdcard",
                // 可选择的类型，file为文件，dir为文件夹
                canChoose: ["dir"],
                // 选择文件后的回调
                fileCallback: (file) => {
                    funt(file);
                }
            }).on("dismiss", (dialog) => {})
            .show();

    });
}

function filefz(file, funt,arr) {
    if (!file) return;
    let view = ui.inflate(
        <vertical padding="6 0">
            <text>需要移动的文件后缀名：(多个以“，”分隔)</text>
            <input id="text" />
            <text>常用：</text>
            <horizontal>
                <checkbox text="图像文件" id="check1" marginLeft="4" marginRight="6" />
                <checkbox text="视频文件" id="check2" marginLeft="4" marginRight="6" />
                <checkbox text="音频文件" id="check3" marginLeft="4" marginRight="6" />
            </horizontal>
        </vertical>, null, false
    );
    if (arr){
        view.text.text(arr.join());
    }

    function txtset(checked, val) {
        let str = view.text.text();
        if (checked) {
            view.text.text(str.replace(/[^,]$/, "$&,") + val);
        } else {
            view.text.text(str.replace(new RegExp(val + ",?"), ""));
        }
    }
    view.check1.on("check", checked => txtset(checked, "bmp,jpg,gif,png,jpeg"));
    view.check2.on("check", checked => txtset(checked, "avi,mov,rmvb,rm,flv,mp4,3gp"));
    view.check3.on("check", checked => txtset(checked, "wav,mp3,wma,ogg,flac,aac"));
    // 显示对话框
    dialogs.build({
        customView: view,
        title: "设置文件类型",
        positive: "确定",
        negative: "取消",
        neutral:"清空",
        // view高度超过对话框时是否可滑动
        wrapInScrollView: false,
        // 按下按钮时是否自动结束对话框
        autoDismiss: false
    }).on("neutral",()=>{
        view.text.text("");
    }).on("positive", (dialog) => {
        let str = view.text.text();
        if (str.length === 0) return view.text.setError("输入为空！");
        let arr = str.split(",");
        funt({
            name: arr,
            tofile: file,
            color: materialColors[random(0, materialColors.length - 1)]
        });
        dialog.dismiss();
    }).on("negative", (dialog) => {
        dialog.dismiss();
    }).show();
}
//当离开本界面时保存
ui.emitter.on("pause", () => {
    file.add("data", todoList);
    file.add("moshi", moshiList);
    file.add("iofile", iofile);
    file.add("ismedia", ismedia);
    file.save();
});